my @i = fetch_all('inittab_include')
    or return;

my $redir = '>/dev/null 2>&1';
my %reserved;
my %by_tag;
my %by_cmd;

open I, '/etc/inittab';
while (<I>)
{
    chomp;
    next unless /^(\w+):\d*:(\w+):(.*)/;
    my ($tag, $state, $cmd) = ($1, $2, $3);
    unless ($state =~ /^(respawn|off)$/)
    {
	$reserved{$tag}++;
	next;
    }

    $cmd =~ s!\s*\Q$redir\E\s*$!!;
    $by_tag{$tag} = $cmd;
    $by_cmd{$cmd} = $tag;
}
close I;

my %new;
for (grep ref eq 'HASH', @i)
{
    while (my ($tag, $cmd) = each %$_)
    {
	if ($reserved{$tag} or $^O =~ /solaris/ && $tag =~ /^[tr]/)
	{
	    warn "Reserved inittab tag `$tag'";
	    push @i, $cmd;
	    next;
	}

	my $old = $by_cmd{$cmd};
	if ($new{$cmd} or ($old and $old ne $tag))
	{
	    warn "Duplicate inittab command `$cmd'";
	    next;
	}

	$by_tag{$tag} = $cmd;
	$by_cmd{$cmd} = $tag;

	$new{$cmd} = $tag;
    }

    $_ = undef;
}

for (@i)
{
    unless (ref eq 'ARRAY')
    {
	next unless length;
	$_ = [ $_ ];
    }
    
    for my $cmd (@$_)
    {
	if (exists $new{$cmd})
	{
	    warn "Duplicate inittab command `$cmd'";
	    next;
	}

	$new{$cmd} = $by_cmd{$cmd} || '';
    }
}

my $fallback = 'I000';
my @disabled = map qr/$_/, map +(ref) ? @$_ : $_, fetch_all('inittab_disable');
my $restart;
for my $cmd (keys %new)
{
    my $state = (grep $cmd =~ $_, @disabled) ? 'off' : 'respawn';
    my $tag = $new{$cmd};
    my $match;
    if ($tag)
    {
	$match = qr/^\Q$tag\E:/;
    }
    else
    {
	local $_ = $cmd;
	s!^(/bin/)?su\s+(-\s+)?(\S+)\s+-c\s+["']!!;
	s!^/[^ ]*/!!;

	# try to use a substring of the command basename
	my @opts;
	for my $n (2..4) { push @opts, substr $_, 0, $n }

	until ($tag)
	{
	    my $t = (shift @opts) || $fallback++;
	    next if $t =~ /\W/;
	    $tag = $t unless $reserved{$t}
		or $^O =~ /solaris/ && $t =~ /^[tr]/
		or $by_tag{$t};
	}

	$by_tag{$tag} = $cmd;
	$match = qr/^\w+:\d*:\w+:\Q$cmd\E\s*(>.*)?$/;
    }

    $cmd .= " $redir" unless $cmd =~ m!>\s*/!;
    file_append('/etc/inittab', "$tag:2345:$state:$cmd\n", $match) and $restart++;
}

command('init', 'q') if $restart;
